import json
import logging
import os
import sys
import cv2
import numpy as np
import io
from PIL import Image

from django.http import JsonResponse, HttpResponse
from django.shortcuts import render
from wxcloudrun.models import Counters

# 添加OCR相关路径
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'ocr_python'))
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'demo/ocr_python'))
sys.path.append(os.path.join(os.path.dirname(os.path.dirname(__file__)), 'wx_img'))

# 导入OCR处理模块
import easyocr
from wechat_dialog_extractor import process_image_by_text_first
from wechat_cloud_base import CloudBase

# 初始化云托管客户端
cloud = CloudBase({
  'env': os.environ.get("CLOUD_ENV_ID", "prod-2gor42zka466523c"),  # 从环境变量获取环境ID
  'appid': os.environ.get("CLOUD_APPID", "wx6f2090aff2949331"),  # 从环境变量获取小程序appid
  'secret': os.environ.get("CLOUD_SECRET", "e37214b5c6af9c729e345b8b8ff2472d")  # 从环境变量获取小程序appsecret
})

# 获取对象存储客户端
storage = cloud.getStorage() if hasattr(cloud, 'getStorage') else None

logger = logging.getLogger('log')


def index(request, _):
    """
    获取主页

     `` request `` 请求对象
    """

    return render(request, 'index.html')


def counter(request, _):
    """
    获取当前计数

     `` request `` 请求对象
    """

    rsp = JsonResponse({'code': 0, 'errorMsg': ''}, json_dumps_params={'ensure_ascii': False})
    if request.method == 'GET' or request.method == 'get':
        rsp = get_count()
    elif request.method == 'POST' or request.method == 'post':
        rsp = update_count(request)
    else:
        rsp = JsonResponse({'code': -1, 'errorMsg': '请求方式错误'},
                            json_dumps_params={'ensure_ascii': False})
    logger.info('response result: {}'.format(rsp.content.decode('utf-8')))
    return rsp


def get_count():
    """
    获取当前计数
    """

    try:
        data = Counters.objects.get(id=1)
    except Counters.DoesNotExist:
        return JsonResponse({'code': 0, 'data': 0},
                    json_dumps_params={'ensure_ascii': False})
    return JsonResponse({'code': 0, 'data': data.count},
                        json_dumps_params={'ensure_ascii': False})


def update_count(request):
    """
    更新计数，自增或者清零

    `` request `` 请求对象
    """

    logger.info('update_count req: {}'.format(request.body))

    body_unicode = request.body.decode('utf-8')
    body = json.loads(body_unicode)

    if 'action' not in body:
        return JsonResponse({'code': -1, 'errorMsg': '缺少action参数'},
                            json_dumps_params={'ensure_ascii': False})

    if body['action'] == 'inc':
        try:
            data = Counters.objects.get(id=1)
        except Counters.DoesNotExist:
            data = Counters()
        data.id = 1
        data.count += 1
        data.save()
        return JsonResponse({'code': 0, "data": data.count},
                    json_dumps_params={'ensure_ascii': False})
    elif body['action'] == 'clear':
        try:
            data = Counters.objects.get(id=1)
            data.delete()
        except Counters.DoesNotExist:
            logger.info('record not exist')
        return JsonResponse({'code': 0, 'data': 0},
                    json_dumps_params={'ensure_ascii': False})
    else:
        return JsonResponse({'code': -1, 'errorMsg': 'action参数错误'},
                    json_dumps_params={'ensure_ascii': False})


def ocr_img(request, _):
    """
    OCR图片处理接口，解析图片中的聊天记录
    
    `` request `` 请求对象
    """
    logger.info('ocr_img request received')
    
    if request.method != 'POST' and request.method != 'post':
        return JsonResponse({
            'code': -1, 
            'errorMsg': '请求方式错误，只支持POST请求'
        }, json_dumps_params={'ensure_ascii': False})
    
    try:
        # 解析请求体
        body_unicode = request.body.decode('utf-8')
        body = json.loads(body_unicode)
        
        # 检查必要参数
        if 'fileID' not in body:
            return JsonResponse({
                'code': -1, 
                'errorMsg': '缺少fileID参数'
            }, json_dumps_params={'ensure_ascii': False})
        
        file_id = body['fileID']
        logger.info(f'Processing image with fileID: {file_id}')
        
        # 从对象存储中获取图片
        if not storage:
            return JsonResponse({
                'code': -1, 
                'errorMsg': '云存储客户端未初始化'
            }, json_dumps_params={'ensure_ascii': False})
        
        # 获取图片数据
        try:
            image_data = storage.get_file(file_id)
        except Exception as e:
            logger.error(f'Failed to get file from storage: {str(e)}')
            return JsonResponse({
                'code': -1, 
                'errorMsg': f'获取图片失败: {str(e)}'
            }, json_dumps_params={'ensure_ascii': False})
        
        # 将图片数据转换为OpenCV格式
        nparr = np.frombuffer(image_data, np.uint8)
        image = cv2.imdecode(nparr, cv2.IMREAD_COLOR)
        
        if image is None:
            return JsonResponse({
                'code': -1, 
                'errorMsg': '图片解码失败'
            }, json_dumps_params={'ensure_ascii': False})
        
        # 使用OCR处理图片
        try:
            # 创建临时文件路径保存图片
            temp_dir = '/tmp'
            os.makedirs(temp_dir, exist_ok=True)
            temp_img_path = os.path.join(temp_dir, f'temp_img_{file_id.split("/")[-1]}')
            
            # 保存图片到临时文件
            cv2.imwrite(temp_img_path, image)
            
            # 处理图片并提取对话
            dialogues = process_image_by_text_first(temp_img_path)
            
            # 删除临时文件
            if os.path.exists(temp_img_path):
                os.remove(temp_img_path)
            
            # 返回处理结果
            return JsonResponse({
                'code': 0, 
                'data': dialogues
            }, json_dumps_params={'ensure_ascii': False})
            
        except Exception as e:
            logger.error(f'OCR processing error: {str(e)}')
            return JsonResponse({
                'code': -1, 
                'errorMsg': f'OCR处理失败: {str(e)}'
            }, json_dumps_params={'ensure_ascii': False})
            
    except json.JSONDecodeError:
        return JsonResponse({
            'code': -1, 
            'errorMsg': '请求体解析失败，请确保是有效的JSON格式'
        }, json_dumps_params={'ensure_ascii': False})
    except Exception as e:
        logger.error(f'Unexpected error: {str(e)}')
        return JsonResponse({
            'code': -1, 
            'errorMsg': f'处理请求时发生错误: {str(e)}'
        }, json_dumps_params={'ensure_ascii': False})


def health_check(request, _):
    """
    健康检查接口，用于容器的存活和就绪探针
    
    `` request `` 请求对象
    """
    logger.info('Health check request received')
    return HttpResponse("OK", status=200)
